package org.pro.Net;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

public class ClientHand extends Thread{
    public Socket socket;
    public int playid;
    public Server server;
    public ObjectOutputStream out;
    public ObjectInputStream in;

    public ClientHand(Socket socket,int playid,Server server) throws IOException {
        this.socket=socket;
        this.playid=playid;
        this.server=server;
        this.out=new ObjectOutputStream(socket.getOutputStream());
        out.flush();
        this.in=new ObjectInputStream(socket.getInputStream());
    }
    @Override
    public void run()
    {
        try{
            while(server.running&&!socket.isClosed())
            {
                    //读取消息
                Object obj=in.readObject();
                if(obj instanceof  Natway)
                {
                    Natway msg=(Natway) obj;
                    msg.playerid=this.playid;
                    server.messageQueue.put(msg);

                }
            }
        }
        catch (Exception e) {
            System.err.println("客户端 " + playid + " 连接断开");
        } finally {
            closeConnection();
        }
    }

    public void closeConnection() {
        try {
            if (out != null) out.close();
            if (in != null) in.close();
            if (!socket.isClosed()) socket.close();
            server.clients.remove(this);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    // 向客户端发送消息
    public void sendMessage(Natway msg) {
        try {
            out.writeObject(msg);
            out.flush();
        } catch (IOException e) {
            System.err.println("发送消息失败: " + e.getMessage());
        }
    }

}
